package com.growthgate.bootcommon.util;

import com.googlecode.ipv6.IPv6Address;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import sun.net.util.IPAddressUtil;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;

/**
 * ip工具类
 *
 * @author GrowthGate
 * @date 2020/1/9
 */
public class IpUtils {

    private static final String UNKNOWN = "unknown";
    /** 127.0.0.1 */
    private static final Long LOCALHOST_V4 = 2130706433L;
    /** ::1 */
    private static final BigInteger LOCALHOST_V6 = BigInteger.ONE;

    @Nullable
    public static String getIp(@NotNull HttpServletRequest request) {
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                if (isLocalhost(ip)) {
                    // 根据网卡取本机配置的IP
                    try {
                        InetAddress inet = InetAddress.getLocalHost();
                        ip = inet.getHostAddress();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            // "***.***.***.***".length()
            if (ip != null && ip.length() > 15) {
                // = 15
                int index = ip.indexOf(",");
                if (index > 0) {
                    ip = ip.substring(0, index);
                }
            }
        } catch (Exception ignored) {
        }
        return ip;
    }

    public static boolean isLocalhost(@NotNull String ip) {
        if (isIpv4(ip)) {
            return Objects.equals(LOCALHOST_V4, ipv4ToLong(ip));
        } else if (isIpv6(ip)) {
            return Objects.equals(LOCALHOST_V6, ipv6ToBigInteger(ip));
        } else {
            return false;
        }
    }

    public static boolean isIpv4(@NotNull String ip) {
        return IPAddressUtil.isIPv4LiteralAddress(ip);
    }

    public static long ipv4ToLong(@NotNull String ipv4) {
        // 将ip转化为byte数组
        byte[] bytes = IPAddressUtil.textToNumericFormatV4(ipv4);
        if (bytes == null) {
            throw new IllegalArgumentException("can not parse [" + ipv4 + "]");
        }
        // 将数组每一位的值乘以相应倍率后再相加
        return (Byte.toUnsignedLong(bytes[0]) << 24) + (Byte.toUnsignedLong(bytes[1]) << 16) + (Byte.toUnsignedLong(bytes[2]) << 8) + (Byte.toUnsignedLong(bytes[3]));
    }

    @NotNull
    @Contract(pure = true)
    public static String longToIpv4(long ip) {
        return ((ip >> 24) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + (ip & 0xFF);
    }

    public static boolean isIpv6(@NotNull String ip) {
        return IPAddressUtil.isIPv6LiteralAddress(ip);
    }

    @NotNull
    public static BigInteger ipv6ToBigInteger(@NotNull String ipv6) {
        return IPv6Address.fromString(ipv6).toBigInteger();
    }

    @NotNull
    public static String bigIntegerToIpv6(@NotNull BigInteger ip) {
        return IPv6Address.fromBigInteger(ip).toString();
    }

}
